﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using ImageResizer;
using System.Web;
using Utils;

namespace Infrastructure
{
	public static class ImageResizer
	{
		public static void ResizeImg(string imgPath, int newMaxWidth, int newMaxHeight, int quality)
		{
			
				var photoBytes = File.ReadAllBytes(imgPath);
				var format = Path.GetExtension(imgPath);
				byte[] resized;
				using (var inStream = new MemoryStream(photoBytes))
				{
					using (var outStream = new MemoryStream())
					{
						var settings = new ResizeSettings
						{
							MaxWidth = newMaxWidth,
							MaxHeight = newMaxHeight,
							Format = format
						};
						settings.Add("quality", quality.ToString());
						ImageBuilder.Current.Build(inStream, outStream, settings);
						resized = outStream.ToArray();
					}
				}
				
				File.WriteAllBytes(imgPath,
					 resized);			
		}

        public static void ResizeImg(string imgPath, string imgPathNew, int newMaxWidth, int newMaxHeight, int quality)
        {

            var photoBytes = File.ReadAllBytes(imgPath);
            var format = Path.GetExtension(imgPath);
            byte[] resized;
            using (var inStream = new MemoryStream(photoBytes))
            {
                using (var outStream = new MemoryStream())
                {
                    var settings = new ResizeSettings
                    {
                        MaxWidth = newMaxWidth,
                        MaxHeight = newMaxHeight,
                        Format = format
                    };
                    settings.Add("quality", quality.ToString());
                    ImageBuilder.Current.Build(inStream, outStream, settings);
                    resized = outStream.ToArray();
                }
            }

            File.WriteAllBytes(imgPathNew,
                 resized);
        }

		public static string MoveImgToContent(string imageUrl, string newImageUrl, string width, string height)
		{
			var imageName = Path.GetFileName(imageUrl);
			imageUrl = HttpContext.Current.Server.MapPath(imageUrl);

			if (!Directory.Exists(HttpContext.Current.Server.MapPath(newImageUrl)))
			{
				Directory.CreateDirectory(HttpContext.Current.Server.MapPath(newImageUrl));
			}

			newImageUrl = HttpContext.Current.Server.MapPath(newImageUrl) + @"\" + (imageName);

			if ((imageUrl != newImageUrl) && (!String.IsNullOrWhiteSpace(Path.GetExtension(newImageUrl))))
			{
				if (File.Exists(newImageUrl))
					File.Delete(newImageUrl);

				File.Copy(imageUrl, newImageUrl);
				if (!String.IsNullOrWhiteSpace(width) && !String.IsNullOrWhiteSpace(height))
					ImageResizer.ResizeImg(newImageUrl, Convert.ToInt32(width), Convert.ToInt32(height), 100);
			}

			return URLUtils.ToVirtualPath(newImageUrl);
		}
		
	}
}
